<?
// +----------------------------------------------------------------------
// | ThinkCt框架[基于ThinkPHP6.0开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.thinkct.net
// +----------------------------------------------------------------------
// | ThinkCt承诺基础框架商业版永久免费技术支持，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 时光网络 <66983239@qq.com>，开发者QQ群：61162800 付费QQ群：250059867
// +----------------------------------------------------------------------php
/**
 * 微极速微信支付
 * @author mapeijian
 */
namespace app\common\pay;

use think\Db;
use app\common\Pay;
use thinkct\library\Purchase;

require_once ROOT_PATH . 'extend/Epay/lib/epay_submit.class.php';
require_once ROOT_PATH . 'extend/Epay/lib/epay_notify.class.php';

class Epay extends Pay
{
    protected $code='';
    protected $error='';

    public function getCode()
    {
        return $this->code;
    }

    public function getError()
    {
        return $this->error;
    }

    public function getConfig()
    {
		$account = plugin_account('epay');// 获取插件账号
        $config  = [
            'apiurl'        => $account['apiurl'],		
            'partner'       => $account['partner'],
            'key'           => $account['key'],
            'sign_type'     => strtoupper('MD5'),
            'input_charset' => strtoupper('utf-8'),
            'transport'     => strtoupper('http'),
        ];
        return $config;
    }
    /**
     * 支付
     * @param string $outTradeNo 外部单号
     * @param string $subject 标题
     * @param float $totalAmount 支付金额
     */
    public function order($data,$paytype) {
        $notify_url = sysconf('site_domain')."/aform/notify_url/epay";
        //需http://格式的完整路径，不能加?id=123这类自定义参数

        //页面跳转同步通知页面路径
        //$return_url = sysconf('site_domain')."/member/lists/money";
		$return_url = sysconf('site_domain')."/aform/notify_url/epay";
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
 		if($paytype == 'qpay') {			
			$paytype = 'qqpay';
		}
		if($paytype == 'wechat') {
			$paytype = 'wxpay';
		}       
        $config = $this->getConfig();
        $subject = ($data['type']=='online')?'在线充值':'在线收银';
		$subject = sysconf('site_name').$subject;		
        $parameter = array(
            "pid"           => trim($config['partner']),
            "type"          => $paytype,
            "notify_url"	=> $notify_url,
            "return_url"	=> $return_url,
            "out_trade_no"	=> $data['bh'].'|'.$data['ubh'],
            "name"	        => $subject,
            "money"	        => $data['money1'],
            "sitename"	    => $subject
        );

        $alipaySubmit = new \AlipaySubmit($config);
        $result = $alipaySubmit->buildRequestForm($parameter);

        //$this->code    =0;
        //$obj           =new \stdClass();
        //$obj->pay_url  =$result;
        //$obj->content_type = 3;
        return $result;
    }

    /**
     * 支付同步通知处理
     */
    public function page_callback($params,$order) {
        header("Location:" . url('/orderquery',['orderid'=>$order->trade_no]));
    }

    /**
     * 支付异步通知处理
     */
    public function notify_callback() {

        $config = $this->getConfig();
        //计算得出通知验证结果
        $alipayNotify = new \AlipayNotify($config);
        $verify_result = $alipayNotify->verifyNotify();
		
		if(empty($_POST)) $_POST = $_GET;
		
		// 验证成功
        if($verify_result) {
			
            // 商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            // 彩虹易支付交易号
            $trade_no = $_POST['trade_no'];
            // 交易状态
            $trade_status = $_POST['trade_status'];
			// 支付金额
			$money = $_POST['money'];
            // 支付方式
            $type = $_POST['type'];
			// 订单参数
			$dingdanbh = explode("|",$out_trade_no);

            if ($trade_status == 'TRADE_SUCCESS') {
				// 获取订单信息
				$row = Db::name('dingdang')->where([
					'ddbh' => $out_trade_no,
					'ddzt' => '等待买家付款',
					'ubh'  => $dingdanbh[1]
				])->find();
		
				if($row) {	
					// 判断支付金额是否一致
					if($money != $row['money1']) {
						return $this->error('支付金额不一致','/member/lists/money');
					}				
					if($trade_status == "TRADE_SUCCESS" || $trade_status == "TRADE_FINISHED" || $trade_status == "WAIT_SELLER_SEND_GOODS"){
						// 在线充值
						if($row['type'] == 'online') {							
							PointUpdate($row['ubh'],$money,"支付宝充值".$money."元");					
						}
						// 在线购买
						if($row['type'] == 'cashier') {
							// 1执行入款
							PointUpdate($row['ubh'],$money,"支付宝充值".$money."元");
							// 2开始购买商品
							$buy = Purchase::index($out_trade_no);
							if($buy == false) {
								$this->success('订单号不存在');
							}
						}
						// 更改状态
						Db::name('dingdang')->where(['ubh'=>$row['ubh'],'ddbh'=>$out_trade_no])->update([
							'sj'       => sj(),
							'alipayzt' => $trade_status,
							'ddzt'     => '支付成功'
						]);						
						// 首次支付成功301转跳
						return redirect("/member/success/".$row['type'])->remember();	
					}					
				}
				// 订单已支付、结束
				if($row['alipayzt'] == "TRADE_SUCCESS" || $row['alipayzt'] == "TRADE_FINISHED"){					
					return $this->success('已经支付成功！','/member/lists/money');
				}
				//return 'success';
				$this->success('已经支付成功！','/member/lists/money');				
			}else{
				record_file_log('wxpay_notify_error','验签错误！'."\r\n".$order->trade_no);
				// 验证失败
				$this->error('验签错误');
			}
		}
	}
}
?>